#!/bin/env/python3
from werkzeug.datastructures import FileStorage

from . import profile_blue
from flask import render_template, jsonify, redirect, g, request, current_app
from info import constants, db
from ...models import News, Category, User
from ...utils import image_storage
from ...utils.commons import user_login_data
from ...utils.response_code import RET


@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        paginate = g.user.followed.paginate(page, 1, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取作者失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    author_list = []
    for item in items:
        author_list.append(item.to_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "author_list": author_list
    }
    print(totalPage, currentPage)
    return render_template("news_/user_follow.html", data=data)


@profile_blue.route('/news_list', methods=['GET'])
@user_login_data
def news_list():
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        paginate = g.user.news_list.order_by(News.create_time.desc()).paginate(page, 3, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    print(totalPage, currentPage)
    return render_template("news_/user_news_list.html", data=data)


@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == "GET":
        try:
            news_cate = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取分类失败")
        news_cate_list = []
        for cate in news_cate:
            news_cate_list.append(cate.to_dict())
        print(news_cate_list)
        return render_template("news_/user_news_release.html", news_cate_list=news_cate_list)
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        image_name = image_storage.image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")
    if not image_name:
        return jsonify(errno=RET.NODATA, errmsg="图片上传失败")
    news_obj = News()
    news_obj.title = title
    news_obj.category_id = category_id
    news_obj.content = content
    news_obj.source = g.user.nick_name
    news_obj.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news_obj.digest = digest
    news_obj.user_id = g.user.id
    news_obj.status = 1
    #  保存数据
    try:
        db.session.add(news_obj)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")
    return jsonify(errno=RET.OK, errmsg="发布成功")


@profile_blue.route('/collection')
@user_login_data
def collection():
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        paginate = g.user.collection_news.order_by(News.create_time.desc()).paginate(page, 2, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    print(totalPage, currentPage)
    return render_template("news_/user_collection.html", data=data)


@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template("news_/user_pass_info.html", user_info=g.user.to_dict())
    if request.method == "POST":
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")
        if not all([new_password, old_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        if not g.user.check_passowrd(old_password):
            return jsonify(errno=RET.DATAERR, errmsg="密码错误")
        g.user.password = new_password
    return jsonify(errno=RET.OK, errmsg="修改成功")


@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    if request.method == "GET":
        print(g.user.to_dict())
        return render_template("news_/user_pic_info.html", user_info=g.user.to_dict())
    avatar = request.files.get("avatar")
    print(type(avatar))
    if not all([avatar]):
        return jsonify(errno=RET.PARAMERR, errmsg="图片不能为空")
    try:
        image_name = image_storage.image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")
    if not image_name:
        return jsonify(errno=RET.NODATA, errmsg="图片上传失败")
    g.user.avatar_url = image_name
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + image_name
    }
    return jsonify(errno=RET.OK, errmsg="图片上传成功", data=data)


@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    if request.method == "GET":
        return render_template('news_/user_base_info.html', user_info=g.user.to_dict())

    # post请求 更改数据
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if not gender in ["MAN", "WOMEN"]:
        return jsonify(errno=RET.DATAERR, errmsg="性别异常")
    g.user.signature = signature
    g.user.nick_name = nick_name
    g.user.gender = gender
    # 返回响应
    return jsonify(errno=RET.OK, errmsg="修改成功")


@profile_blue.route('/user_index')
@user_login_data
def user_index():
    if not g.user:
        return redirect("/")
    data = {
        "user_info": g.user.to_dict()
    }
    return render_template("news_/user.html", data=data)
